
//
//  LoginViewController.m
//  HuaRun2
//
//  Created by admin on 17/9/4.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "LoginViewController.h"
#import "PasswordInputView.h"
#import "AppLogoView.h"
#import "UserModel.h"
#import "NSBundle+Language.h"
#import "EAIntroView.h"
#import "PopForgetPsdView.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "ZLGestureLockViewController.h"

@interface LoginViewController () <EAIntroDelegate>
//logo
@property(nonatomic, strong) AppLogoView * appLogoView;
//用户名
@property(nonatomic, strong) PasswordInputView * userNameInputView;
//密码
@property(nonatomic, strong) PasswordInputView * psdInputView;
//登陆按钮
@property(nonatomic, strong) UIButton * submitBtn;
//忘记按钮
@property(nonatomic, strong) UIButton * forgetPsdBtn;
//记住按钮
@property(nonatomic, strong) UIButton * remberPsdBtn;
@property (nonatomic, strong)PopForgetPsdView * popForgetPsdView;

@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // Do any additional setup after loading the view.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewInit {

    [super viewInit];
    
    [self.view addSubview:self.appLogoView];
    [self.view addSubview:self.userNameInputView];
    [self.view addSubview:self.psdInputView];
    [self.view addSubview:self.submitBtn];
    [self.view addSubview:self.forgetPsdBtn];
    [self.view addSubview:self.remberPsdBtn];
    
    if (_isFirstLaunch) {
        [self configureIntroPage];
    }

}

- (void)dataInit {
    BOOL isRememberPsd = [[NSUserDefaults standardUserDefaults] boolForKey:@"isRememberPsd"];
    self.remberPsdBtn.selected = isRememberPsd;
    NSLog(@"---%@ %@", _remberPsdBtn.selected ? @"记住": @"忘记", isRememberPsd ? @"yes" : @"no");

    if (isRememberPsd) {
        UserModel * userModel = [UserModel getCurrentUserModel];
        _userNameInputView.textField.text = [NSString isemptyStr:userModel.name] ? @"" :
        userModel.name;
        _psdInputView.textField.text = [NSString isemptyStr:userModel.password] ? @"" :
        userModel.name;
    }
}

- (void) configureIntroPage {
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView.image = [UIImage imageNamed:@"欢迎页1"];
    EAIntroPage *page1 = [EAIntroPage pageWithCustomView:imageView];
    
    UIImageView * imageView2 = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView2.image = [UIImage imageNamed:@"欢迎页2"];
    EAIntroPage *page2 = [EAIntroPage pageWithCustomView:imageView2];
    
    UIImageView * imageView3 = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView3.image = [UIImage imageNamed:@"欢迎页3"];
    EAIntroPage *page3 = [EAIntroPage pageWithCustomView:imageView3];
    
    EAIntroView * introView = [[EAIntroView alloc] initWithFrame:self.view.bounds
                                                        andPages:@[page1,
                                                                   page2,
                                                                   page3]];
    
    UIButton * skipBtn = [UIButton new];
    skipBtn.frame = CGRectMake(0, 0, 150, 40);
    skipBtn.backgroundColor = [UIColor whiteColor];
    [skipBtn setTitle:NSLocalizedString(@"go_home", nil)
                forState:(UIControlStateNormal)];
    [skipBtn setTitleColor:RGBA(243, 161, 50, 1)
                    forState:(UIControlStateNormal)];
    skipBtn.layer.cornerRadius = 18;
    skipBtn.layer.masksToBounds = YES;
    skipBtn.layer.borderColor = RGBA(243, 161, 50, 1).CGColor;
    skipBtn.layer.borderWidth = 1;
    introView.skipButton = skipBtn;
    introView.skipButtonAlignment = EAViewAlignmentCenter;
    introView.showSkipButtonOnlyOnLastPage = YES;
    [introView showInView:self.view animateDuration:0];
}

- (void)layoutInit {
    [super layoutInit];
    
    weakself(ws);
    [self.appLogoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ws.view).offset(110);
        make.centerX.mas_equalTo(ws.view);
    }];

    [self.userNameInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.view).offset(50);
        make.right.mas_equalTo(ws.view).offset(-50);
        make.top.mas_equalTo(ws.appLogoView.mas_bottom).offset(110);
    }];

    [self.psdInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.userNameInputView);
        make.top.mas_equalTo(ws.userNameInputView.mas_bottom).offset(kMargin10);
    }];

    [self.forgetPsdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(ws.userNameInputView);
        make.top.mas_equalTo(ws.psdInputView.mas_bottom).offset(kMargin10);
        make.height.mas_equalTo(25);
        make.width.mas_equalTo(100);
    }];
    
    [self.remberPsdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.userNameInputView);
        make.top.mas_equalTo(ws.forgetPsdBtn);
        make.height.mas_equalTo(25);
//        make.width.mas_equalTo(80);
    }];

    [self.submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.userNameInputView);
        make.top.mas_equalTo(ws.forgetPsdBtn.mas_bottom).offset(20);
        make.height.mas_equalTo(40);
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark method
- (void)forgetPsdMethod {
    UIWindow * window = [UIApplication sharedApplication].keyWindow;

    weakself(ws);
    self.popForgetPsdView = [[PopForgetPsdView alloc] initWithFrame:self.view.bounds];
    [_popForgetPsdView.waibuLabEmail addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        
        BOOL isCanCopy = [ToolHelper copyWithText:@"Kelvin@cre.com.hk"];
        if (isCanCopy) {
            [ws showAlert:NSLocalizedString(@"copy_success", nil)];
        }

    }];
    
    [_popForgetPsdView.neibuLab addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        [ToolHelper openWebWithUrlStr:kForgetPsdUrl];
    }];
    
    [window addSubview:self.popForgetPsdView];
}

- (void)remeberPsdMethod {
    _remberPsdBtn.selected = !_remberPsdBtn.selected;
}

//登陆方法
- (void)loginMethod:(UIButton *)btn {
//    [self isCanUseTouchID];
//    self.isFirstLaunch = NO;
////    return;
    
    [self.view endEditing:YES];
    btn.userInteractionEnabled = NO;
    
//    return;
    
    NSString * userName = _userNameInputView.textField.text;
    NSString * password = _psdInputView.textField.text;
    if (userName.length == 0) {
        btn.userInteractionEnabled = YES;
        [self showWithText:NSLocalizedString(@"请输入用户名", nil)];
        return;
    }
    if (password.length == 0) {
        btn.userInteractionEnabled = YES;
        [self showWithText:NSLocalizedString(@"请输入密码", nil)];
        return;
    }
//    NSLog(@"之前的UserModel 0000---- %@", [UserModel getCurrentUserModel]);
//    return;
//    NSString * name = @"huangroujun@nfh.hk";
//    NSString * password = @"1";
    NSString * kWidthStr = [NSString stringWithFormat:@"%.fpt", kMainScreenWidth];
    NSString * kHeightStr = [NSString stringWithFormat:@"%.fpt", kMainScreenHeight];

    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kLoginUrl];
    NSDictionary * dic = @{@"password": password,
                           @"name": userName,
                           @"imsi": [NSString IMSIString]? [NSString IMSIString]: @"",
                           @"mnc": [NSString carrierNameString],
                           @"model": [NSString deviceString],
                           @"osVersion": [NSString iosVersions],
                           @"screenWidth": kWidthStr,
                           @"screenHeight": kHeightStr};
//    return;
    [self showActivity:NSLocalizedString(@"正在登录",nil)];
    weakself(ws);
    [NetWorkHelper postWithURLString:url parameters:dic success:^(id object) {
        [ws hideAllAlert];
        
        btn.userInteractionEnabled = YES;
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        
        NSDictionary * tempDic = object[@"obj"];
        if (![tempDic isKindOfClass: [NSNull class]]) {
            UserModel * userModel = [UserModel yy_modelWithJSON:tempDic[@"user"]];
            userModel.access_token = tempDic[@"access_token"];
            userModel.refresh_token = tempDic[@"refresh_token"];
            userModel.password = password;
            
            NSString * boundleLange = @"";
            if ([userModel.language isEqualToString:@"zh_CN"]) {
                boundleLange = @"zh-Hans";
            }else if ([userModel.language isEqualToString:@"zh_HK"]) {
                boundleLange = @"zh-Hant";
            }else if ([userModel.language isEqualToString:@"en_US"]) {
                boundleLange = @"en";
            }
            [ws changeLanguageTo:boundleLange];
            
            [[NSUserDefaults standardUserDefaults] setBool:ws.remberPsdBtn.selected
                                                    forKey:@"isRememberPsd"];
            
            BOOL isRememberPsd = [[NSUserDefaults standardUserDefaults] boolForKey:@"isRememberPsd"];
            NSLog(@"%@ %@", _remberPsdBtn.selected ? @"记住": @"忘记", isRememberPsd ? @"yes" : @"no");

            [UserModel saveUserModel:userModel];
            NSLog(@"%@", [UserModel getCurrentUserModel]);
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isLoginState];

        }
        
        if (_isFirstLaunch) {
            [ws isUseTouchIdMethod];
        }else {
            if (ws.isPresentStyle) {
                [ws.navigationController dismissViewControllerAnimated:YES completion:^{

                    ws.clickBlock ? ws.clickBlock(@""): nil;
                }];
            }else {
            
                ws.clickBlock ? ws.clickBlock(@""): nil;
            }
        }
    } failure:^(NSError *error) {
        [ws hideAllAlert];

        btn.userInteractionEnabled = YES;

        [ws showWithText:kNetworkError];
    }];
}
     
#pragma mark getter 

- (AppLogoView *)appLogoView {
    if (!_appLogoView) {
        self.appLogoView = [AppLogoView new];
    }
    return _appLogoView;
}

- (PasswordInputView *)userNameInputView {
    if (!_userNameInputView) {
        self.userNameInputView = [PasswordInputView new];
        _userNameInputView.nameLab.text = NSLocalizedString(@"Account", nil);
        _userNameInputView.iconView.image = [UIImage imageNamed:@"用户名"];
//        _userNameInputView.textField.text = @"huangroujun@nfh.hk";
        _userNameInputView.textField.placeholder =NSLocalizedString(@"请输入用户名", nil);
        _userNameInputView.iconView.hidden = YES;
    }
    return _userNameInputView;
}

- (PasswordInputView *)psdInputView {
    if (!_psdInputView) {
        self.psdInputView = [PasswordInputView new];
        _psdInputView.nameLab.text = NSLocalizedString(@"password", nil);
        _psdInputView.iconView.image = [UIImage imageNamed:@"密码"];
//        _psdInputView.textField.text = @"1";
        _psdInputView.textField.secureTextEntry = YES;
        _psdInputView.textField.placeholder = NSLocalizedString(@"请输入密码", nil);
        _psdInputView.iconView.hidden = YES;
    }
    return _psdInputView;
}
- (UIButton *)submitBtn {
    if (!_submitBtn) {
        self.submitBtn = [UIButton new];
        _submitBtn.backgroundColor = RGBA(243, 161, 50, 1);
        [_submitBtn setTitle:NSLocalizedString(@"登录", nil)
                    forState:(UIControlStateNormal)];
        _submitBtn.layer.cornerRadius = 5;
        _submitBtn.layer.masksToBounds = YES;
        [_submitBtn addTarget:self action:@selector(loginMethod:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _submitBtn;
}

- (UIButton *)forgetPsdBtn {
    if (!_forgetPsdBtn) {
        self.forgetPsdBtn = [UIButton new];
        [_forgetPsdBtn setTitle:NSLocalizedString(@"忘记密码?",nil)
                       forState:(UIControlStateNormal)];
        [_forgetPsdBtn setTitleColor:[UIColor grayColor]
                            forState:(UIControlStateNormal)];
        [_forgetPsdBtn.titleLabel setFont:kGeneralFontSize];
        _forgetPsdBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_forgetPsdBtn addTarget:self action:@selector(forgetPsdMethod) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _forgetPsdBtn;
}

- (UIButton *)remberPsdBtn {
    if (!_remberPsdBtn) {
        self.remberPsdBtn = [UIButton new];
        [_remberPsdBtn setTitle: [NSString stringWithFormat:@" %@",
         NSLocalizedString(@"remember_password",nil)]
                       forState:(UIControlStateNormal)];
        [_remberPsdBtn setTitleColor:[UIColor grayColor]
                         forState:(UIControlStateNormal)];
        [_remberPsdBtn.titleLabel setFont:kGeneralFontSize];
        [_remberPsdBtn setImage:[UIImage imageNamed:@"记住密码1"] forState:(UIControlStateNormal)];
        [_remberPsdBtn setImage:[UIImage imageNamed:@"记住密码2"] forState:(UIControlStateSelected)];
        _remberPsdBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_remberPsdBtn addTarget:self action:@selector(remeberPsdMethod) forControlEvents:(UIControlEventTouchUpInside)];
        [_remberPsdBtn sizeToFit];
    }
    return _remberPsdBtn;
}

- (void)changeLanguageTo:(NSString *)language {
    // 设置语言
    [NSBundle setLanguage:language];
    
    // 然后将设置好的语言存储好，下次进来直接加载
    [[NSUserDefaults standardUserDefaults] setObject:language
                                              forKey:@"myLanguage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationResetLanguage object:nil];
}

//询问用户是否使用touch id
- (void)isUseTouchIdMethod {
    //            "cancel"= "取消";
    //            "confirm" = "确定";
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"isUseTouchId", nil)                                                    message:NSLocalizedString(@"isUseTouchId", nil)
                                                   delegate:self
                                          cancelButtonTitle:
                           NSLocalizedString(@"cancel", nil)
                                          otherButtonTitles:NSLocalizedString(@"confirm", nil),nil];
    [alert show];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"%ld", buttonIndex);
    [[NSUserDefaults standardUserDefaults] setBool:buttonIndex == 1 forKey:@"isUseTouchId"];

    //取消
    if (buttonIndex == 0) {
        
//        确定
    }else if (buttonIndex == 1) {
        
    }
    [self pushGestureLockView];

}

- (void)isCanUseTouchID {
    //创建LAContext
    LAContext *context = [[LAContext alloc] init];
    // 这个属性是设置指纹输入失败之后的弹出框的选项
    context.localizedFallbackTitle = @"请输入密码";
    
    weakself(ws);
    NSError *error = nil;
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        [self isUseTouchIdMethod];
    }else {
        
        [self showAlert:NSLocalizedString(@"cantSupportTouchID", nil) completionBlock:^{
            [ws pushGestureLockView];
        }];

    }

}

// 验证指纹
- (void)authenticateUser {
    //创建LAContext
    LAContext *context = [[LAContext alloc] init];
    // 这个属性是设置指纹输入失败之后的弹出框的选项
    context.localizedFallbackTitle = @"请输入密码";
    
    NSError *error = nil;
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        NSLog(@"支持指纹识别");
        // localizedReason: 用于设置提示语，表示为什么要使用Touch ID
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"请按home键指纹解锁" reply:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update UI in UI thread here
                    NSLog(@"验证成功 刷新主界面");
                });
            }else{
                NSLog(@"%@",error.localizedDescription);
                switch (error.code) {
                    case LAErrorSystemCancel:
                    {
                        NSLog(@"系统取消授权，如其他APP切入");
                        break;
                    }
                    case LAErrorUserCancel:
                    {
                        NSLog(@"用户取消验证Touch ID");
                        break;
                    }
                    case LAErrorAuthenticationFailed:
                    {
                        NSLog(@"授权失败");
                        break;
                    }
                    case LAErrorPasscodeNotSet:
                    {
                        NSLog(@"系统未设置密码");
                        break;
                    }
                    case LAErrorTouchIDNotAvailable:
                    {
                        NSLog(@"设备Touch ID不可用，例如未打开");
                        break;
                    }
                    case LAErrorTouchIDNotEnrolled:
                    {
                        NSLog(@"设备Touch ID不可用，用户未录入");
                        break;
                    }
                    case LAErrorUserFallback: // 用于设置左边的按钮的名称，默认是Enter Password
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            NSLog(@"用户选择输入密码，切换主线程处理");
                        }];
                        break;
                    }
                    default:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            NSLog(@"其他情况，切换主线程处理");
                        }];
                        break;
                    }
                }
            }
        }];
    }else{
        
        NSLog(@"不支持指纹识别");
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:
            {
                NSLog(@"TouchID is not enrolled");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                NSLog(@"A passcode has not been set");
                break;
            }
            default:
            {
                NSLog(@"TouchID not available");
                break;
            }
        }
        
        NSLog(@"%@",error.localizedDescription);
    }
}

//去设置手势密码
- (void)pushGestureLockView {
    ZLGestureLockViewController *loginVC =  [[ZLGestureLockViewController alloc] initWithUnlockType:ZLUnlockTypeCreatePsw];
    
    weakself(ws);
    loginVC.clickBlock = ^(id result) {
        
        if (ws.isPresentStyle) {
            [ws.navigationController dismissViewControllerAnimated:YES completion:^{

                ws.clickBlock ? ws.clickBlock(@""): nil;
            }];
        }else {
            ws.clickBlock ? ws.clickBlock(@""): nil;
        }
    };
    [self.navigationController pushViewController:loginVC animated:YES];

}

@end
